'use client'

import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Check } from 'lucide-react'
import { useRouter } from 'next/navigation'
import { _signUpWithGoogle } from '@/utils/firebase.js'
import useRequest from '@/utils/request'
import { useEffect, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { selectUser, setUser } from '@/store/user-slice'

const pricing = [
  {
    value: 'monthly',
    label: 'Monthly',
    priceSuffix: '/month',
    plans: [
      {
        name: 'Free',
        price: '$0',
        features: [
          '10 keywords',
          '2 replies/mo',
          '1 project',
          'Auto-replies',
          'Email notifications',
          'Reports',
          '24/7 Support',
        ],
        mostPopular: false,
      },
      {
        name: 'Small',
        price: '$5.99',
        features: [
          '15 keywords',
          '30 replies/mo',
          '1 project',
          'Auto-replies',
          'Email notifications',
          'Reports',
          '24/7 Support',
        ],
        mostPopular: false,
      },
      // {
      //   name: 'Pro',
      //   price: '$39.99',
      //   features: [
      //     '15 keywords',
      //     '120 replies/mo',
      //     '1 project',
      //     'Auto-replies',
      //     'Email notifications',
      //     'Reports',
      //     '24/7 Support',
      //   ],
      //   mostPopular: false,
      // },
      {
        name: 'Lifetime',
        price: '$199',
        features: [
          '100 keywords',
          '1000 replies/mo',
          'Unlimited project',
          'Auto-replies',
          'Email notifications',
          'Reports',
          '24/7 Support',
        ],
        mostPopular: true,
      },
      // {
      //   name: 'Business',
      //   price: '$99',
      //   features: [
      //     '25 keywords',
      //     '300 replies/mo',
      //     '5 project',
      //     'Auto-replies',
      //     'Email notifications',
      //     'Reports',
      //     '24/7 Support',
      //   ],
      //   mostPopular: false,
      // },
    ],
  },
  {
    value: 'yearly',
    label: 'Yearly',
    priceSuffix: '/year',
    plans: [
      {
        name: 'Free',
        price: '$0',
        features: [
          '10 keywords',
          '2 replies/mo',
          '1 project',
          'Auto-replies',
          'Email notifications',
          'Reports',
          '24/7 Support',
        ],
        mostPopular: false,
      },
      {
        name: 'Small',
        price: '$35',
        features: [
          '15 keywords',
          '30 replies/mo',
          '1 project',
          'Auto-replies',
          'Email notifications',
          'Reports',
          '24/7 Support',
        ],
        mostPopular: false,
      },
      // {
      //   name: 'Pro',
      //   price: '$239',
      //   features: [
      //     '15 keywords',
      //     '120 replies/mo',
      //     '1 project',
      //     'Auto-replies',
      //     'Email notifications',
      //     'Reports',
      //     '24/7 Support',
      //   ],
      //   mostPopular: false,
      // },
      {
        name: 'Lifetime',
        price: '$1194',
        features: [
          '100 keywords',
          '1000 replies/mo',
          'Unlimited project',
          'Auto-replies',
          'Email notifications',
          'Reports',
          '24/7 Support',
        ],
        mostPopular: true,
      },
      // {
      //   name: 'Business',
      //   price: '$594',
      //   features: [
      //     '25 keywords',
      //     '300 replies/mo',
      //     '5 project',
      //     'Auto-replies',
      //     'Email notifications',
      //     'Reports',
      //     '24/7 Support',
      //   ],
      //   mostPopular: false,
      // },
    ],
  },
]

function classNames(...classes) {
  return classes.filter(Boolean).join(' ')
}

export default function Pricing({ showTitle = true }) {
  const router = useRouter()
  const request = useRequest()
  const user = useSelector(selectUser)
  const [products, setProducts] = useState([])
  const dispatch = useDispatch()

  useEffect(() => {
    const fetchData = async () => {
      const res = await request.get(`pay2/products`)
      setProducts(res.data)
    }

    fetchData()
  }, [])

  const buy = async (name, type) => {
    if (user?.token) {
      if (name === 'Free') {
        router.push('/projects')
      } else {
        const prodcut = products.filter(product => product.name === name)
        const { product_id, store_id, variants } = prodcut[0]

        let index = -1
        // if (name === 'Lifetime') {
        //   index = 0
        // } else {
        index = type === 'monthly' ? 1 : 2
        // }

        const data = {
          product_id,
          store_id,
          variant_id: variants[index].id,
        }
        const res = await request.post(`pay2/checkout`, data)
        location.href = res.data.url
      }
    } else {
      try {
        const data = await _signUpWithGoogle()
        const res = await request.post('account/signin_or_signup_with_source', data)
        dispatch(setUser(res.data))
      } catch (error) {
        console.log(error)
      }
    }
  }

  return (
    <div className="bg-white py-12 md:py-16">
      <main>
        <div className="mx-auto max-w-7xl px-6 lg:px-8">
          {showTitle && (
            <div className="mx-auto max-w-4xl text-center">
              <h2 className="mt-2 text-4xl font-bold tracking-tight text-gray-900 sm:text-5xl">
                Simple, transparent pricing
              </h2>
            </div>
          )}
          <p className="mx-auto mt-6 max-w-2xl text-center text-lg leading-8 text-gray-600">
            Get <span className="text-[#ff5c5c]">6 months</span> free with the yearly plan✨!
          </p>
          <Tabs defaultValue="monthly" className="mt-3">
            <TabsList className="mx-auto w-fit flex justify-center">
              {pricing.map(one => {
                return (
                  <TabsTrigger key={one.value} value={one.value}>
                    {one.label}
                  </TabsTrigger>
                )
              })}
            </TabsList>
            {pricing.map(one => {
              return (
                <TabsContent key={one.value} value={one.value}>
                  <div className="isolate mx-auto mt-10 grid max-w-md grid-cols-1 gap-8 md:max-w-2xl md:grid-cols-2 lg:max-w-4xl xl:mx-0 xl:max-w-none xl:grid-cols-3">
                    {one.plans.map(plan => (
                      <div
                        key={`${one.value}_${plan.name}`}
                        className={classNames(
                          plan.mostPopular ? 'ring-2 ring-[#ff5c5c]' : 'ring-1 ring-gray-200',
                          'rounded-3xl p-8'
                        )}
                      >
                        <h2
                          id={plan.name}
                          className={classNames(
                            plan.mostPopular ? 'text-[#ff5c5c]' : 'text-gray-900',
                            'text-lg font-semibold leading-8'
                          )}
                        >
                          {plan.name}
                        </h2>
                        <p className="mt-6 flex items-baseline gap-x-1">
                          <span className="text-4xl font-bold tracking-tight text-gray-900">{plan.price}</span>
                          {plan.name !== 'Lifetime' && (
                            <span className="text-sm font-semibold leading-6 text-gray-600">{one.priceSuffix}</span>
                          )}
                        </p>
                        <ul role="list" className="mt-8 space-y-3 text-sm leading-6 text-gray-600">
                          {plan.features.map(feature => (
                            <li key={`${one.value}_${feature}`} className="flex gap-x-3">
                              <Check className="h-6 w-5 flex-none text-[#ff5c5c]" aria-hidden="true" />
                              {feature}
                            </li>
                          ))}
                        </ul>
                        <a
                          onClick={() => buy(plan.name, one.value)}
                          aria-describedby={plan.name}
                          className={classNames(
                            plan.mostPopular
                              ? 'bg-[#ff5c5c] text-white shadow-sm hover:bg-[#fa8d8d]'
                              : 'text-[#ff5c5c] ring-1 ring-inset ring-[#ff5c5c] hover:ring-[#ff5c5c]',
                            'mt-6 block rounded-md py-2 px-3 text-center text-sm font-semibold leading-6 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[#ff5c5c]'
                          )}
                        >
                          Get started today
                        </a>
                      </div>
                    ))}
                  </div>
                </TabsContent>
              )
            })}
          </Tabs>
        </div>
      </main>
    </div>
  )
}
